package aufgabe1_mit_threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {
	
	//Port des Servers
	int port;
	
	// Soll der Server laufen
	boolean run_server;
	
	// Logger
	Logger logger;
	
	// Reffernce auf Master
	Server_Administration_Control_I_for_Server control;
	
	/**
	 * Constructor for Server Verwaltet anfragen an einem Port
	 * @param server_a Server_Administration
	 * @param port int Server Port
	 */
	public Server(int port, Server_Administration_Control_I_for_Server control,Logger logger) {
		
		this.port = port;
		this.control = control;
		this.logger = logger;
		run_server = true;
		setDaemon(true);
		
		logger.log("Server", "Server", "Erzeugt");
	}

	@Override
	public void run() {
		logger.log("Server", "Server", "run");
		//Server Socket
		ServerSocket server;
		
		//Server Socket Erstellen
		try {
			server = new ServerSocket(port);
		
			logger.log("Server", "Server","Maintaining");
			while(run_server){
					
				if(control.is_place_for_threads()){
					
					Socket conection = null;
					logger.log("Server", "Server", "Warte auf Connect");
					conection = server.accept();
					control.server_thread_counter_up();
					logger.log("Server", "Server Thread", "Connect");
					new Server_Thread(conection, (Server_Administration_Control_I_for_Server_Tread)control,logger).start();
					logger.log("Server", "Server Thread", "Start");
				} else {
					my_sleep();
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		logger.log("Server", "Server", "Closing");
	}

	public void my_sleep(){
		try {
			sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	synchronized public void stop_runing() {
		logger.log("Server", "Server",  "Starte Closing");
		run_server = false;
	}
}